package com.meida.base.provider.handler;

import com.meida.common.constants.CommonConstants;
import com.meida.common.base.entity.EntityMap;
import com.meida.common.mybatis.interceptor.SaveInterceptor;
import com.meida.common.mybatis.query.CriteriaSave;
import com.meida.common.security.OpenHelper;
import com.meida.common.base.utils.FlymeUtils;
import com.meida.common.utils.StringUtils;
import com.meida.module.admin.client.constants.BaseConstants;
import com.meida.module.admin.client.entity.BaseUser;
import com.meida.module.admin.provider.service.BaseAccountService;
import com.meida.module.system.client.entity.SysCompany;
import com.meida.module.system.provider.service.SysCompanyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 后台用户添加扩展
 *
 * @author zyf
 */
@Component
public class AdminUserAddHandler implements SaveInterceptor<BaseUser> {

    @Autowired
    private SysCompanyService companyService;
    @Resource
    private BaseAccountService baseAccountService;

    @Override
    public void prepare(CriteriaSave cs, EntityMap params, BaseUser baseUser) {
        Long companyId = OpenHelper.getCompanyId();
        Integer superAdmin = OpenHelper.getUser().getSuperAdmin();
        if (CommonConstants.INT_0.equals(superAdmin)) {
            SysCompany company = companyService.getById(companyId);
            if (FlymeUtils.isNotEmpty(company)) {
                baseUser.setOrganizationId(company.getOrganizationId());
            }
        }

    }

    @Override
    public void complete(CriteriaSave cs, EntityMap params, BaseUser baseUser) {
        //默认注册用户名账户
        if (FlymeUtils.isNotEmpty(baseUser.getUserName())) {
            if (!baseUser.getUserName().equals(baseUser.getMobile())) {
                baseAccountService.register(baseUser.getUserId(), baseUser.getUserName(), baseUser.getPassword(), BaseConstants.USER_ACCOUNT_TYPE_USERNAME, baseUser.getStatus(), BaseConstants.ACCOUNT_DOMAIN_ADMIN, null);
            }
        }
        if (StringUtils.matchEmail(baseUser.getEmail())) {
            //注册email账号登陆
            baseAccountService.register(baseUser.getUserId(), baseUser.getEmail(), baseUser.getPassword(), BaseConstants.USER_ACCOUNT_TYPE_EMAIL, baseUser.getStatus(), BaseConstants.ACCOUNT_DOMAIN_ADMIN, null);

        }
        if (StringUtils.matchMobile(baseUser.getMobile())) {
            //注册手机号账号登陆
            baseAccountService.register(baseUser.getUserId(), baseUser.getMobile(), baseUser.getPassword(), BaseConstants.USER_ACCOUNT_TYPE_MOBILE, baseUser.getStatus(), BaseConstants.ACCOUNT_DOMAIN_ADMIN, null);
        }
    }
}
